/**
 * load extra groups.
 */

var errorCodes = require("../ErrorCode/errCode.js");
var accountTable = require("../Redis/accountTable.js");
var redis = require("../Redis/redis.js");
var gatewayTable = require("../Redis/gatewayTable.js");

function reply(context) {
	"use strict";
	var res = context.res;
	var groups = context.groups;
	
	res.writeHead(200);
	res.end(JSON.stringify(groups));
}

function loadGroupWith(context) {
	"use strict";
	var res = context.res;
	var groupIds = context.groupIds;
	
	var cb = function(err, reply) {
		if (err) {
			console.error("loadGroup error:" + err);
		} else {
			if (reply) {
				var group = JSON.parse(reply);
				context.groups.push(group);
				
			} else {
				console.error("load group error, group not exist");
			}
		}
	};
	
	context.beginMulti();
	
	groupIds.forEach(function(gIdPair){
		gatewayTable.loadGroup(context, gIdPair.gwId, gIdPair.groupId, cb);
	});
	
	context.endMulti(function(err) {
		if (err) {
			errorCodes.errorEnd(errorCodes.ERR_DATABASE, ""+err, res);
		} else {
			reply(context);
		}
	});
}

function loadGroupHandler(req, res, account) {
	"use strict";
	var context = {};
	context.groups = [];
	context.res = res;
	
	redis.setClient(context);
	
	accountTable.loadFields(context, account, ["groups"], function(err, replies){
		if (err) {
			errorCodes.errorEnd(errorCodes.ERR_DATABASE, ""+err, res);
		} else {
			var groupIds = null;
			var jgroupIds = replies[0];
			if (!jgroupIds) {
				groupIds = JSON.parse(jgroupIds);
			}
			
			if (!groupIds || groupIds.length < 1) {
				reply(context);
				return;
			}
			
			context.groupIds = groupIds;
			loadGroupWith(context);
		}
	});
}

module.exports = loadGroupHandler;
